package com.xjcs.saplingplan.base

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.viewbinding.ViewBinding
import com.blankj.utilcode.util.BarUtils
import com.xjcs.saplingplan.dialog.LoadingDialog
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


abstract class BaseVbActivity<VB : ViewBinding> : AppCompatActivity() {

    lateinit var mBinding: VB

    private var loadingDialog: LoadingDialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        BarUtils.transparentStatusBar(this)
        super.onCreate(savedInstanceState)
        mBinding = getViewBinding()
        setContentView(mBinding.root)
        init(savedInstanceState)
    }

    private fun init(savedInstanceState: Bundle?) {
        registerObserver()
        initUi(savedInstanceState)
        initListener()
        BarUtils.setStatusBarLightMode(this, true)
    }

    /**
     * 默认的事件处理方法
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun onEvent(event: Any) {
        // 子类可以重写此方法以处理特定事件
    }

    /**
     * 创建viewBinding
     */
    abstract fun getViewBinding(): VB

    /**
     * UI初始化
     */
    abstract fun initUi(savedInstanceState: Bundle?)

    /**
     * 创建LiveData数据观察者
     */
    abstract fun registerObserver()

    /**
     * 点击事件
     */
    abstract fun initListener()

    fun showLoading() {
        if (loadingDialog == null) {
            loadingDialog = LoadingDialog(this)
        }
        loadingDialog?.show()
    }

    fun hideLoading() {
        loadingDialog?.dismiss()
    }

    override fun onDestroy() {
        super.onDestroy()
        //防止内存泄漏
        loadingDialog?.dismiss()
        loadingDialog = null
    }

    override fun onStart() {
        super.onStart()
        // 注册 EventBus
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
    }

    override fun onStop() {
        super.onStop()
        // 注销 EventBus
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }

}